﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

namespace Framework.WebmasterTool.FileManagers
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "AddedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadFileManager();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.DownloadFile.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadFileManager()
        {
            var files = entity.udv_Files.Select(fm => new { fm.FileID, fm.Title, fm.aspnet_Users.UserName, fm.FileType, fm.FileSize, fm.AddedDate, fm.DisplayOrder, fm.IsActive }).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                files = files.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                files = files.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvFileManager.DataSource = files;
            grvFileManager.DataBind();
        }

        protected void grvFileManager_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvFileManager.ToolTip == "all")
                LoadFileManager();
            else
                SearchFileManager();
        }

        protected void grvFileManager_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvFileManager.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvFileManager_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvFileManager.PageIndex = e.NewPageIndex;
            if (grvFileManager.ToolTip == "all")
                LoadFileManager();
            else
                SearchFileManager();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvFileManager.PageIndex = 0;
            grvFileManager.ToolTip = "search";
            SearchFileManager();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvFileManager.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int fileID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    var file = entity.udv_Files.Where(fi => fi.FileID == fileID).FirstOrDefault();
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_FileDownload_Folder_MapPath + file.FileURL));

                    //create db log
                    CreateDBLog(null, null, TypeAction.Delete, "Xoá quản lý file: " + file.Title, file.Description, "", "", "",
                        file.IsActive.Value.ToString(), "", "", "");

                    entity.DeleteObject(file);
                    entity.SaveChanges();
                }
            }
            //data cache
            Cache.Remove("File");
            ////clear outputcache
            //HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            //HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
            //HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
            //HttpResponse.RemoveOutputCacheItem("/Products.aspx");
            //HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
            //HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
            if (grvFileManager.ToolTip == "all")
                LoadFileManager();
            else
                SearchFileManager();
        }

        public void SearchFileManager()
        {
            var files = entity.udv_Files.Select(fm => new { fm.FileID, fm.Title, fm.aspnet_Users.UserName, fm.FileType, fm.FileSize, fm.AddedDate, fm.DisplayOrder, fm.IsActive }).ToList();
            if (txtSearch.Text.Trim() != "")
            {
                string keywordSearch = Globals.RemoveSign4VietnameseString(txtSearch.Text.Trim().ToLower());
                files = files.Where(fi => Globals.RemoveSign4VietnameseString(fi.Title.ToLower()).Contains(keywordSearch) || fi.UserName.ToLower().Contains(keywordSearch) || fi.FileType.ToLower().Contains(keywordSearch) || fi.AddedDate.Value.ToString("dd/MM/yyyy").Contains(keywordSearch)).ToList();
            }
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                files = files.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                files = files.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvFileManager.DataSource = files;
            grvFileManager.DataBind();
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}